import React, { useState, useEffect } from 'react';
import { View, Button, Alert, Text } from 'react-native';
import RNFS from 'react-native-fs';
import { unzip } from 'react-native-zip-archive';
import RNRestart from 'react-native-restart';
import AsyncStorage from '@react-native-async-storage/async-storage';

const VERSION_URL = 'https://you/update.json';
const LOCAL_VERSION_KEY = 'LOCAL_VERSION';
const DEFAULT_VERSION = '1.0.0';

// 版本号比较函数
function compareVersion(v1: string, v2: string) {
  const arr1 = v1.split('.').map(Number);
  const arr2 = v2.split('.').map(Number);
  for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
    const n1 = arr1[i] || 0;
    const n2 = arr2[i] || 0;
    if (n1 > n2) return 1;
    if (n1 < n2) return -1;
  }
  return 0;
}

export default function App() {
  const [updating, setUpdating] = useState(false);
  const [localVersion, setLocalVersionState] = useState(DEFAULT_VERSION);

  useEffect(() => {
    // 启动时读取本地版本号
    (async () => {
      const storedVersion = await AsyncStorage.getItem(LOCAL_VERSION_KEY);
      const ver = storedVersion || DEFAULT_VERSION;
      setLocalVersionState(ver);
      checkAndUpdate(ver); // 传入读取的本地版本
    })();
  }, []);

  const checkAndUpdate = async (currentVersion?: string) => {
    const localVer = currentVersion || localVersion;

    try {
      const res = await fetch(VERSION_URL);
      const updateInfo = await res.json();

      if (!updateInfo.version || compareVersion(updateInfo.version, localVer) <= 0) {
        console.log('已是最新版本');
        return; // ✅ 不弹窗
      }

      Alert.alert(`发现新版本 ${updateInfo.version}`, updateInfo.desc || '', [
        { text: '开始更新', onPress: () => downloadUpdate(updateInfo) },
        { text: '取消', style: 'cancel' },
      ]);
    } catch (error) {
      console.error('检查更新失败', error);
    }
  };

  const downloadUpdate = async (updateInfo: any) => {
    try {
      setUpdating(true);

      if (!updateInfo.downloadUrl) {
        throw new Error('更新下载地址不存在');
      }

      const destPath = `${RNFS.DocumentDirectoryPath}/update.zip`;
      console.log('开始下载更新包...', updateInfo.downloadUrl);

      const result = await RNFS.downloadFile({
        fromUrl: encodeURI(updateInfo.downloadUrl),
        toFile: destPath,
        progressDivider: 10,
        progress: (p) =>
          console.log(`下载进度: ${((p.bytesWritten / p.contentLength) * 100).toFixed(0)}%`),
      }).promise;

      if (result.statusCode === 200) {
        const targetPath = `${RNFS.DocumentDirectoryPath}/update`;
        await unzip(destPath, targetPath);
        console.log('解压完成', targetPath);

        // 更新本地版本号
        await AsyncStorage.setItem(LOCAL_VERSION_KEY, updateInfo.version);
        setLocalVersionState(updateInfo.version);

        Alert.alert('更新完成', '应用将重启以应用新版本', [
          { text: '确定', onPress: () => RNRestart.Restart() },
        ]);
      } else {
        Alert.alert('下载失败', `HTTP 状态码 ${result.statusCode}`);
      }
    } catch (error: any) {
      console.error('下载更新失败', error);
      Alert.alert('下载更新失败', error.message || error.toString());
    } finally {
      setUpdating(false);
    }
  };

  return (
    <View style={{ marginTop: 100, padding: 20 }}>
      <Button
        title={updating ? '更新中...' : '手动检查更新'}
        onPress={() => checkAndUpdate()}
        disabled={updating}
      />
      <Text style={{ marginTop: 20, textAlign: 'center' }}>
        当前版本: {localVersion}
      </Text>
    </View>
  );
}
